import 'package:example/base/http_resp_exception.dart';
import 'package:example/utils/common.dart';
import 'package:example/utils/string_ext.dart';
import 'package:dio/dio.dart';

import '../data/bean/base_response.dart';


/// Future 扩展
extension FutureExt on Future {

  /// 转换为对象
  Future<BaseResponse<T?>> handlerException<T>(
      {bool isToast = true, bool ignoreError = false,bool isDelayed = false}) async {
    BaseResponse<T?> resp;
    try {
      resp = await this;
    } on DioException catch (e) {
      if (e.error is HttpRespException) {
        HttpRespException exception = e.error as HttpRespException;
        resp = BaseResponse(code: exception.code, msg: exception.message);
      } else {
        resp = BaseResponse(code: -1, msg: e.error.toString());
      }
    } on BaseResponse catch (e) {
      // 防止多次调用handlerException
      resp = BaseResponse(code: e.code, msg: e.msg);
    } catch (e) {
      resp = BaseResponse(code: -1, msg: e.toString());
    }

    return _handlerException<T>(resp, isToast: isToast, ignoreError: ignoreError,isDelayed: isDelayed);
  }

  Future<String> toOssUrl(String url) async {
    await this;
    return url;
  }

  _convert(dynamic result, BaseResponse defaultResult,
      BaseResponse Function(dynamic json) fun) {
    dynamic json;
    if (result is String) {
      json = result.toJson();
    } else {
      json = result;
    }

    try {
      defaultResult = fun.call(json);
    } catch (e) {
      logger.e(e);
      loggerJson.e(
          '数据解析异常或${defaultResult.data.toString()}没有在DataConvert的convert里面配置：\njson -> $json');
      defaultResult.code = -1;
      defaultResult.msg = "数据解析异常";
    }
    return defaultResult;
  }

  /// 解析异常
  Future<BaseResponse<T?>> _handlerException<T>(BaseResponse<T?> resp,
      {bool isToast = true, bool ignoreError = false,bool isDelayed = false}) async {
    if (!resp.isSuccess()) {
      if (resp.code == 40001) {
        // logout();
      }
      if (!ignoreError) {
        if (isToast) showToast(resp.msg ?? "未知异常");
        logger.e("请求失败:${resp.code ?? ""}:${resp.msg ?? "未知异常"}");
        return Future.error(resp);
      }
    }
    if(isDelayed){
      return Future.delayed(const Duration(milliseconds: 500)).then((value) => resp);
    }
    return resp;
  }

}
